package com.myapp.ruyixing.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.Model;

public class PhoneRegisterFragment extends Fragment implements OnClickListener {

	String mPhoneNumber = "";
	Button mGetVerifyCodeButton;

	private Handler mCountDownHandler = new Handler() {
		private int countdown = 60;

		public void reset() {
			countdown = 60;
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				reset();
			}

			if (countdown != 0) {
				mGetVerifyCodeButton.setEnabled(false);
				mGetVerifyCodeButton.setText("重新获取验证码（" + countdown + "s）");
				countdown--;
				sendEmptyMessageDelayed(0, 1000);
			} else {
				mGetVerifyCodeButton.setEnabled(true);
				mGetVerifyCodeButton.setText("点击获取验证码");
			}
		}
	};

	private void showToast(String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

	private void showLoading(boolean show, String msg) {
		Activity activity = getActivity();
		IShowLoading showLoading = null;
		try {
			showLoading = (IShowLoading) activity;
		} catch (Exception e) {
			return;
		}
		showLoading.showLoading(show, msg);
	}

	public PhoneRegisterFragment() {
		// Required empty public constructor
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.fragment_register_phone, container,
				false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		view.findViewById(R.id.btn_register).setOnClickListener(this);
		view.findViewById(R.id.btn_register_go).setOnClickListener(this);
		view.findViewById(R.id.btn_commit).setOnClickListener(this);
		view.findViewById(R.id.text_agree).setOnClickListener(this);
		mGetVerifyCodeButton = (Button) view.findViewById(R.id.btn_get_verify);
		mGetVerifyCodeButton.setEnabled(false);
		mGetVerifyCodeButton.setOnClickListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	private void commitPhoneNumber(String num) {
		showLoading(true, "加载中");
		RYHttpClient.sendPhone(getActivity(), new RYHttpResponseHandler() {

			@Override
			public void onSuccess(Object o) {
				try {
					Model model = (Model) o;
					onCommitPhoneNumberFinished(model.errno);
				} catch (Exception e) {
					onCommitPhoneNumberFinished(-1);
				}
			}

			@Override
			public void onFailure(Throwable throwable) {
				onCommitPhoneNumberFinished(-1);
			}
		}, num);
	}

	private void onCommitPhoneNumberFinished(int errno) {
		showLoading(false, "加载中");
		switch (errno) {
		case 0:
			((TextView) getView().findViewById(R.id.text_dianhua))
					.setText(mPhoneNumber);
			showLayout(2);
			Message.obtain(mCountDownHandler, 1).sendToTarget();
			break;
		case 1:
			showToast("此手机号不可用！");
			break;
		case 2:
			showToast("此手机号不可用！");
			break;
		case 3:
			showToast("此手机号已被注册过！");
			break;

		default:
			break;
		}
	}

	private void commitICode(String phone, String icode) {
		showLoading(true, "加载中");
		RYHttpClient.checkICode(getActivity(), new RYHttpResponseHandler() {

			@Override
			public void onSuccess(Object o) {
				try {
					Model model = (Model) o;
					onCommitICodeFinished(model.errno);
				} catch (Exception e) {
					onCommitICodeFinished(-1);
				}
			}

			@Override
			public void onFailure(Throwable throwable) {
				onCommitICodeFinished(-1);
			}
		}, phone, icode);
	}

	private void onCommitICodeFinished(int errno) {
		showLoading(false, "加载中");
		switch (errno) {
		case 0:
			showLayout(3);
			break;
		case 1:
			showToast("验证码不能为空！");
			break;
		case 2:
			showToast("验证码错误！");
			break;

		default:
			break;
		}
	}

	private void register(String phone, String username, String password) {
		showLoading(true, "加载中");
		RYHttpClient.register(getActivity(), new RYHttpResponseHandler() {

			@Override
			public void onSuccess(Object o) {
				try {
					Model model = (Model) o;
					onRegisterFinished(model.errno);
				} catch (Exception e) {
					onRegisterFinished(-1);
				}
			}

			@Override
			public void onFailure(Throwable throwable) {
				onRegisterFinished(-1);
			}
		}, phone, username, password);
	}

	private void onRegisterFinished(int errno) {
		showLoading(false, "加载中");
		switch (errno) {
		case 0:
			showToast("注册成功，请登陆！");
			getActivity().finish();
			break;
		case 1:
			showToast("用户名或密码不能为空！");
			break;
		case 2:
			showToast("用户名已存在！");
			break;

		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.btn_register:
			String text = ((EditText) getView().findViewById(R.id.edit_phone))
					.getText().toString();
			if (TextUtils.isEmpty(text) || text.length() != 11) {
				showToast("请输入11位手机号码");
			} else {
				mPhoneNumber = text;
				commitPhoneNumber(text);
			}
			break;
		case R.id.btn_register_go:
			String code = ((EditText) getView().findViewById(R.id.edit_verify))
					.getText().toString();
			if (TextUtils.isEmpty(code) || code.length() != 6) {
				showToast("请输入6位验证码！");
			} else {
				commitICode(mPhoneNumber, code);
			}
			break;
		case R.id.btn_commit:
			if (!((CheckBox) getView().findViewById(R.id.check_agree))
					.isChecked()) {
				showToast("请阅读协议后勾选同意！");
				return;
			}
			String username = ((EditText) getView().findViewById(
					R.id.edit_nickname)).getText().toString();
			String password = ((EditText) getView().findViewById(
					R.id.edit_password)).getText().toString();
			if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
				showToast("用户名或密码不能为空！");
			} else {
				register(mPhoneNumber, username, password);
			}
			break;
		case R.id.text_agree:
			intent = new Intent(getActivity(), AgreementActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_get_verify:
			commitPhoneNumber(mPhoneNumber);
			break;

		default:
			break;
		}
	}

	private void showLayout(int no) {
		View view = getView();
		if (view == null) {
			return;
		}
		switch (no) {
		case 1:
			view.findViewById(R.id.layout_first_step).setVisibility(
					View.VISIBLE);
			view.findViewById(R.id.layout_second_step).setVisibility(View.GONE);
			view.findViewById(R.id.layout_third_step).setVisibility(View.GONE);
			break;
		case 2:
			view.findViewById(R.id.layout_first_step).setVisibility(View.GONE);
			view.findViewById(R.id.layout_second_step).setVisibility(
					View.VISIBLE);
			view.findViewById(R.id.layout_third_step).setVisibility(View.GONE);
			break;
		case 3:
			view.findViewById(R.id.layout_first_step).setVisibility(View.GONE);
			view.findViewById(R.id.layout_second_step).setVisibility(View.GONE);
			view.findViewById(R.id.layout_third_step).setVisibility(
					View.VISIBLE);
			break;

		default:
			break;
		}
	}
}
